from constr_budgets.models import Materials, Project, Modules, \
    MaterialsHistory,People
from django.views import View
from django.http import JsonResponse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
import json
from utils.Infinite import infinite
import time
import datetime

class Materialss(View):
    def get(self, req):
        try:
            page = req.GET.get('page')
            page_size = req.GET.get('pagesize')
            project_id = req.GET.get('project_id')
            end_time = req.GET.get("end_time")
        except :
            return JsonResponse({'code': 304, 'msg': "数据有误"})
        material_list = []
        if end_time == "":
            print("aaaa")
            material_list = Materials.objects.filter(project=project_id).values('id', 'project__name', 'modules__name',
                                                                                'materials_price', 'create_time',
                                                                                'modules__unit', 'materials_num')
        else:
            print("bbbb")
            dt = datetime.datetime.strptime(end_time, "%Y-%m-%d")
            ccs = dt.timestamp()
            cc = Materials.objects.filter(project=project_id).values('id', 'project__name', 'modules__name',
                                                                                'materials_price', 'create_time',
                                                                                'modules__unit', 'materials_num')
            for i in cc:
                if i["create_time"].timestamp() <= ccs:
                    material_list.append(i)
        paginator = Paginator(list(material_list), page_size)
        total = paginator.count
        try:
            page_ = paginator.page(page)
        except  PageNotAnInteger:
            page_ = paginator.page(1)
        except EmptyPage:
            page_ = paginator.page(paginator.num_page)
        print(list(page_))
        return JsonResponse({"code": 200, 'msg': "获取成功", 'data': {"data": list(page_), 'total': total},})

    # 根据权限查询对应材料
    def put(self,req):
        data = json.loads(req.body)
        # 通过项目ID找到模板
        getProval = list(Project.objects.filter(id=data['project_id']).values())
        template_id = getProval[0]['templates_id']
        # 通过用户ID找到权限
        getRoleval = list(People.objects.filter(id=data['people_id']).values())[0]['role_auth']
        # 权限中项目对应的模板中的字段ID(材料和非材料)
        role = eval(getRoleval)[int(data['project_id'])]
        # 通过模板ID筛选出和权限对应的所有材料
        MaterialList = Modules.objects.filter(template=template_id, is_materials=1, id__in=role).values()
        lis = list(MaterialList)
        dic = {}
        data = []
        for item in lis:
            dic[item["id"]] = item
        for opt in lis:
            if not opt["pid"]:
                data.append(dic[opt["id"]])
            else:
                try:
                    if "children" not in dic[opt["pid"]]:
                        dic[opt["pid"]]["children"] = []
                except:
                    data.append(dic[opt["id"]]) # 如果没有找不到父级就直接添加到
                    continue
                dic[opt["pid"]]["children"].append(dic[opt["id"]])
        return JsonResponse({'code': 200, 'msg': "获取成功",'data': data})

    def post(self, req):
        data = json.loads(req.body)
        #看是否在数据库内
        isin=list(Materials.objects.filter(modules=data['modules_id'],project=data['project_id']).values())
        if isin:
            #如果在那么将修改数据
            isin=isin[0]
            Materials.objects.filter(modules=data['modules_id'],project=data['project_id']).update(materials_num=int(isin['materials_num'])+int(data['materials_num']),
                                                                                               materials_price=int(isin['materials_price'])+int(data['materials_price']))
            aimMaterials = Materials.objects.get(modules=data['modules_id'],project=data['project_id'])
            aimMaterials.save()
            print('已经存在')
        else:
            #如果不知添加一条初始化记录
            Materials.objects.create(project_id=data['project_id'],modules_id=data['modules_id'],materials_num=data['materials_num'],materials_price=data['materials_price'])
        #之后都会再查询数据sql获取id，添加历史记录，进行关联 获取id
        getId=Materials.objects.get(project=data['project_id'],modules=data['modules_id'])
        print('get到存在的数据：',getId.id)
        # 创建一条新的历史记录
        MaterialsHistory.objects.create(change_num=data['materials_num'],change_price=data['materials_price'],materials_id=getId.id,project_id=data['project_id'])
        return JsonResponse({'code': 200, 'msg': "添加成功"})

class MaterialsHistorys(View):
    def get(self,req):

        page = req.GET.get('page','')
        page_size = req.GET.get('pagesize','')
        keywords=req.GET.get("keywords",'')
        addTime=req.GET.get("add_time",'')
        project_id=req.GET.get("project_id",'')
        MaterialsHistory_value = MaterialsHistory.objects.filter(materials__modules__name__contains=keywords,add_time__contains=addTime,project_id=project_id).values('change_num', 'change_price', 'materials',
                                                                           'materials__modules__name','materials__modules__unit', 'add_time', 'id')
        paginator = Paginator(list(MaterialsHistory_value), page_size)
        total = paginator.count
        try:
            page_ = paginator.page(page)
        except  PageNotAnInteger:
            page_ = paginator.page(1)
        except EmptyPage:
            page_ = paginator.page(paginator.num_page)
        # print(list(page_))
        return JsonResponse({'code': 200, 'msg': "获取成功",'data':{'data':list(page_),"total":total}})

    # 依据权限获取页面数据
    def put(self, req):
        data = json.loads(req.body)
        print(data)
        page = data['page']
        page_size = data['page_size']
        people_id = data['people_id']
        project_id = data['project_id']
        # 通过用户ID找到权限
        getRoleval = list(People.objects.filter(id=people_id).values())[0]['role_auth']
        role = eval(getRoleval)[int(data['project_id'])]
        material_list = Materials.objects.filter(project=project_id,modules__in=role).values('id', 'project__name', 'modules__name',
                                                                            'modules__unit', 'materials_num',
                                                                            'materials_price', 'create_time')
        paginator = Paginator(list(material_list), page_size)
        total = paginator.count
        try:
            page_ = paginator.page(page)
        except  PageNotAnInteger:
            page_ = paginator.page(1)
        except EmptyPage:
            page_ = paginator.page(paginator.num_page)
        # print(list(page_))
        return JsonResponse({"code": 200, 'msg': "获取成功", 'data': {"data": list(page_), 'total': total}, })
